from tortoise.functions import Count

from common.base import Dao
from models.address import Address
from models.user import User
from models.area import Area
from schemas.address import AddressSchemaInput


class AddressDao(Dao):

    async def get(self, **kwargs):
        return await User.get_or_none(**kwargs)

    async def get_user_address(self, user_id):
        """
        查询某个用户总的收获地址数量
        """
        return await self.model.filter(user__id=user_id).count()

    async def create_address(self, address_input: AddressSchemaInput):
        """创建地址"""
        # 1. 查 user
        user = await User.get(pk=address_input.user_id)
        # 2. 查 省
        province = await Area.get(pk=address_input.province_id)
        # 3. 查 市
        city = await Area.get(pk=address_input.city_id)
        # 4. 查区
        district = await Area.get(pk=address_input.district_id)

        # 删除外键
        del address_input.user_id
        del address_input.province_id
        del address_input.city_id
        del address_input.district_id

        # 创建
        return await self.model.create(**address_input.dict(), user=user, province=province, city=city, district=district)

    async def update_address(self, pk, address_input: AddressSchemaInput):
        """修改地址"""
        # 更新
        return await self.model.filter(pk=pk).update(**address_input.dict())

    async def del_address(self, pk):
        """逻辑删除"""
        await self.model.filter(pk=pk).update(is_deleted=True)

    async def arr_address(self, user_id):
        return await self.model.filter(user__id=user_id, is_deleted=False).order_by('-user__default_address_id')

    async def set_default(self, pk, user_id):
        await User.filter(pk=user_id).update(default_address_id=pk)


address_dao = AddressDao(Address)